import * as server_ui from "@minecraft/server-ui";
import * as server from "@minecraft/server";
import * as derived_tools from "../system/derived_tools";
import * as native_tools from "../system/native_tools";
import * as achieve_plan from "../system/achieve_plan";
import * as math_tools from "../system/math_tools";
export function StatefulInspectionTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const message = derived_tools.GetTargetIntel(player);
            if (message.length === 0) {
                player.sendMessage([native_tools.EntityTranslate(player), { text: '-> <§l§9 状态侦测 §r>未能找到你所指向的目标' }]);
                return;
            }
            ;
            if (player instanceof server.Player && player.isSneaking) {
                player.sendMessage([...message, '\n']);
            }
            else if (player instanceof server.Player && !player.isSneaking) {
                new server_ui
                    .ActionFormData()
                    .title('§9<§l 状态信息 §r§9>')
                    .body({ rawtext: message })
                    .button('§4§l关闭§r')
                    .button('§9§l导出§r')
                    .show(player)
                    .then(result => { if (!result.canceled && result.selection == 1)
                    console.warn(JSON.stringify(message)); });
            }
            else {
                server.world.sendMessage([...message, '\n']);
            }
            ;
            player.playSound('conduit.activate');
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function CreativeToolsTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            native_tools.TrySpawnParticle(player.dimension, 'constant:fireworks_fireball_amber_color', math_tools.Vector.add(player.location, { x: 0, y: 3, z: 0 }));
            server.system.run(() => container.setItem(player.selectedSlotIndex));
            player.runCommand('loot spawn ~ ~3 ~ loot create_mode_toolkit');
            player.playSound("conduit.attack");
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function WorldOfBoxTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const options = {
                excludeTypes: ["minecraft:xp_orb"],
                excludeFamilies: ['player'],
                location: player.location,
                maxDistance: 8
            };
            const entitys = player.dimension.getEntities(options);
            const status = player.getDynamicProperty('qiankun_in_the_box:status');
            if (status == undefined) {
                native_tools.TrySpawnParticle(player.dimension, 'constant:smoke_rune_purple', player.location);
                player.sendMessage(`§6|§r 正在<§a 收纳 §r>周围的实体 §6|§r`);
                player.playAnimation("animation.item.common.resist");
                player.playSound("conduit.activate");
                entitys.forEach(entity => entity.tryTeleport(player.getHeadLocation()));
                player.setDynamicProperty('qiankun_in_the_box:status', true);
                server.system.runTimeout(() => player.runCommand(`structure save "${player.id}" ~2~2~2 ~-2~-2~-2 true disk true`), 4);
                server.system.runTimeout(() => entitys.forEach(entity => { if (entity && entity.isValid())
                    entity?.remove(); }), 6);
            }
            else {
                player.runCommand(`structure load "${player.id}" ~-2~-2~-2 0_degrees none true false`);
                native_tools.TrySpawnParticle(player.dimension, 'constant:smoke_rune_purple', player.location);
                player.sendMessage(`§6|§r 正在<§d 释放 §r>储存的实体 §6|§r`);
                player.playAnimation("animation.item.common.resist");
                player.playSound("conduit.activate");
                player.setDynamicProperty('qiankun_in_the_box:status', undefined);
            }
            ;
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function MaterialSortingTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const getEntity = player.getEntitiesFromViewDirection({ maxDistance: 64 })[0]?.entity;
            const getBlock = player.getBlockFromViewDirection({ maxDistance: 64 })?.block;
            player.isSneaking
                ? ExtractEvent(player, getEntity, getBlock, container)
                : InjectEvent(player, getEntity, getBlock, container);
            player.playSound("armor.equip_diamond");
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
function ExtractEvent(player, entity, block, container) {
    const Event = (input) => {
        const StackGroup = [];
        if (input && container) {
            let emptySlots = container.emptySlotsCount - 1;
            for (let α = 0; α < input.size; α++) {
                const getItem = input.getItem(α);
                if (emptySlots == 0)
                    continue;
                if (!getItem)
                    continue;
                StackGroup.push(getItem);
                input.setItem(α);
                emptySlots -= 1;
            }
            ;
            for (let α of StackGroup)
                container.addItem(α);
            player.sendMessage(`§7正在远程抽取物品, < 您的背包 >的剩余空间为§r:§2 ${emptySlots}`);
        }
    };
    if (entity) {
        const getContainer = entity.getComponent('minecraft:inventory')?.container;
        if (getContainer)
            Event(getContainer);
        else
            player.sendMessage(`§7无法获取实体:§6<§c ${entity.typeId} §6>§7的容器信息`);
    }
    else if (block) {
        const getContainer = block.getComponent('minecraft:inventory')?.container;
        if (getContainer)
            Event(getContainer);
        else {
            const title = {
                text: "<§8§o§l 物资清除 §r>§9操作界面"
            };
            const option = [
                { text: '§c§l掉落物清理§r' }
            ];
            const labelα = { text: '物资整理 -> 删除' };
            const labelβ = {
                text: "§6设置§r<§a 清理范围 §r>"
            };
            new server_ui.ModalFormData()
                .title(title)
                .dropdown(labelα, option, 0)
                .slider(labelβ, 8, 255, 1, 64)
                .show(player).then(option => {
                if (option.canceled)
                    return;
                native_tools.TrySpawnParticle(player.dimension, 'constant:general_tips', math_tools.Vector.add(player.getHeadLocation(), { x: 0, y: 1.5, z: 0 }));
                player.runCommand(`kill @e[type=item,r=${option.formValues[1]}]`);
                player.sendMessage("§4掉落物已销毁, 该操作不可撤销!");
            });
        }
    }
}
;
function InjectEvent(player, entity, block, container) {
    const Event = (input) => {
        if (!container)
            return;
        container.setItem(player.selectedSlotIndex);
        const StackGroup = [];
        if (!input)
            return;
        let emptySlots = input.emptySlotsCount;
        for (let α = 0; α < container.size; α++) {
            const getItem = container.getItem(α);
            if (emptySlots == 0)
                continue;
            if (!getItem)
                continue;
            StackGroup.push(getItem);
            container.setItem(α);
            emptySlots -= 1;
        }
        for (let α of StackGroup)
            input.addItem(α);
        player.sendMessage(`§7正在远程注入物品, < 目标容器 >的剩余空间为§r:§2 ${emptySlots}`);
    };
    if (entity) {
        const getContainer = entity.getComponent('minecraft:inventory')?.container;
        if (getContainer)
            Event(getContainer);
        else
            player.sendMessage(`§7无法获取实体:§6<§c ${entity.typeId} §6>§7的容器信息`);
    }
    else if (block) {
        const getContainer = block.getComponent('minecraft:inventory')?.container;
        if (getContainer)
            Event(getContainer);
        else
            player.sendMessage(`§7无法获取方块:§6<§c ${block.typeId} §6>§7的容器信息`);
    }
}
;
export function ContainerSorting(player, block) {
    const container = block?.getComponent('minecraft:inventory')?.container;
    const items = [];
    if (!container)
        return;
    for (let index = 0; index < container.size; index++) {
        const item = container.getItem(index);
        if (!item)
            continue;
        container.setItem(index);
        items.push(item);
    }
    ;
    items.sort((a, b) => a.typeId.split(/:/)[1].length - b.typeId.split(/:/)[1].length);
    items.sort((a, b) => a.amount - b.amount);
    for (let item of items)
        container.addItem(item);
    player.playSound("armor.equip_diamond");
}
;
export function InhibitWaterTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const block = player.getBlockFromViewDirection({ includeLiquidBlocks: true, maxDistance: 128 })?.block;
            if (!block || block.typeId !== 'minecraft:water')
                return;
            if (!player.isSneaking) {
                native_tools.TryFillBlocks(block.dimension, math_tools.Vector.add(block.location, { x: 5, y: 5, z: 5 }), math_tools.Vector.add(block.location, { x: -5, y: -5, z: -5 }), 'block_unit:unreal_space', {
                    blockFilter: { includePermutations: [server.BlockPermutation.resolve('minecraft:water')] }
                });
                native_tools.TryFillBlocks(block.dimension, math_tools.Vector.add(block.location, { x: 4, y: 4, z: 4 }), math_tools.Vector.add(block.location, { x: -4, y: -4, z: -4 }), 'minecraft:air', {
                    blockFilter: { includePermutations: [server.BlockPermutation.resolve('block_unit:unreal_space')] }
                });
            }
            else
                native_tools.TryFillBlocks(block.dimension, math_tools.Vector.add(block.location, { x: 5, y: 5, z: 5 }), math_tools.Vector.add(block.location, { x: -5, y: -5, z: -5 }), 'minecraft:air', { blockFilter: { includePermutations: [server.BlockPermutation.resolve('minecraft:water')] } });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function NihilitySpaceBlockTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 2))
                return;
            const target = player.dimension.getBlock(math_tools.Vector.add(player.location, math_tools.Vector.CONSTANT_DOWN));
            if (target && target.isAir)
                target.setPermutation(server.BlockPermutation.resolve('block_unit:nihility_space'));
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function PurpleGoldGourdTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 80))
                return;
            const state = item.getDynamicProperty('item:stage.purple_gold_gourd') ?? 0;
            const time = item.getDynamicProperty('item:time.purple_gold_gourd') ?? 0;
            const save = item.getDynamicProperty('item:save.purple_gold_gourd') ?? 'minecraft:tnt';
            const entity = player.getEntitiesFromViewDirection({ maxDistance: 64 })[0]?.entity;
            switch (state) {
                case 0:
                    player.playSound('speak.crystal.purple_gold_gourd.start');
                    item.setDynamicProperty('item:stage.purple_gold_gourd', 1);
                    break;
                case 1:
                    if (!entity || !entity.isValid())
                        return player.playSound('speak.crystal.purple_gold_gourd.fail');
                    player.playSound('speak.crystal.purple_gold_gourd.catch');
                    item.setDynamicProperty('item:stage.purple_gold_gourd', 2);
                    item.setDynamicProperty('item:time.purple_gold_gourd', server.system.currentTick);
                    item.setDynamicProperty('item:save.purple_gold_gourd', entity.typeId);
                    native_tools.TrySpawnParticle(player.dimension, 'constant:excite_rune_purple', entity.location);
                    native_tools.TrySpawnParticle(player.dimension, 'constant:smoke_rune_purple', entity.location);
                    native_tools.TrySpawnParticle(player.dimension, 'constant:erupt_rune_purple', entity.location);
                    derived_tools.UnloadInventoryAndDestroy(entity);
                    break;
                case 2:
                    if (server.system.currentTick - time <= 1200)
                        return player.playSound('speak.crystal.purple_gold_gourd.wait');
                    const target = native_tools.TrySpawnEntity(player.dimension, save, player.location);
                    item.setDynamicProperty('item:stage.purple_gold_gourd', 0);
                    player.playSound('speak.crystal.purple_gold_gourd.done');
                    if (target instanceof server.Entity)
                        target.kill();
                    break;
            }
            ;
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
